﻿using Microsoft.Win32;

namespace MsBuildAxTasks
{
    public class AxConfigProfile
    {
        public string BinDir { get; set; }
        public string LogDir { get; set; }
        public string Config { get; private set; }
        public string Version { get; private set; }

        public AxConfigProfile(string _version)
        {
            Version = _version;
            Config = DefaultConfigProfile();

            Init();
        }

        public AxConfigProfile(string _version, string _profile)
        {
            Version = _version;

            if (string.IsNullOrEmpty(_profile))
                Config = DefaultConfigProfile();
            else
                Config = _profile;

            Init();
        }

        private void Init()
        {
            RegistryKey axConfigurationRegKey = GetDynamicsRegKey().OpenSubKey("Configuration");

            BinDir = axConfigurationRegKey.OpenSubKey(Config).GetValue("bindir").ToString();
            LogDir = axConfigurationRegKey.OpenSubKey(Config).GetValue("logdir").ToString();
        }

        private RegistryKey GetDynamicsRegKey()
        {
            RegistryKey dynamicsRegKey = null;

            try
            {
                dynamicsRegKey = Registry.CurrentUser
                                            .OpenSubKey("Software")
                                                .OpenSubKey("Microsoft")
                                                    .OpenSubKey("Dynamics")
                                                        .OpenSubKey(Version);

                if (dynamicsRegKey == null)
                {
                    throw new AxNotInstalledException("Unable to find valid client instalation. Dynamics Ax version " + Version + " not installed.");
                }

                dynamicsRegKey.OpenSubKey("Configuration");
            }
            catch
            {
                throw new AxNotInstalledException("Unable to find valid client instalation. Dynamics Ax version " + Version + " not installed.");
            }

            return dynamicsRegKey;
        }

        private string DefaultConfigProfile()
        {
            return GetDynamicsRegKey().OpenSubKey("Configuration").GetValue("Current").ToString();
        }
    }
}
